package com.core.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.system.utils.SecurityUser;
import com.pojo.entity.ImMessageRecordEntity;
import com.core.system.dao.ImMessageRecordMapper;
import com.core.system.service.IImMessageRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pojo.req.im.ImRecordDto;
import com.pojo.req.im.ImRecordReq;
import com.pojo.req.im.ImRecordResp;
import com.utility.constant.Constant;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.List;

/**
 * <p>
 * 用户消息记录 服务实现类
 * </p>
 *
 * @author hewei
 * @since 2023-10-21
 */
@Service
public class ImMessageRecordServiceImpl extends ServiceImpl<ImMessageRecordMapper, ImMessageRecordEntity> implements IImMessageRecordService {


    @Override
    public Page<ImRecordResp> page(ImRecordReq imRecordReq) {
        ImRecordDto imRecordDto = new ImRecordDto();
        imRecordDto.setMyChatIdentifier(Base64.getEncoder().encodeToString((SecurityUser.getUserId() + "" + imRecordReq.getUserId()).getBytes()));
        imRecordDto.setYourChatIdentifier(Base64.getEncoder().encodeToString((imRecordReq.getUserId()+SecurityUser.getUserId()+"").getBytes()));
        return this.baseMapper.selectImRecord(new Page<>(imRecordReq.getCurrentPage(),imRecordReq.getPageSize()),imRecordDto);
    }


    /**
     * 获取 limit 条聊天记录
     * @param userId
     * @param limit
     * @return
     */
    public List<ImRecordResp> list(Long userId,Integer limit) {
        ImRecordDto imRecordDto = new ImRecordDto();
        imRecordDto.setMyChatIdentifier(Base64.getEncoder().encodeToString((userId+""+SecurityUser.getUserId()).getBytes()));
        imRecordDto.setYourChatIdentifier(Base64.getEncoder().encodeToString((SecurityUser.getUserId() + "" + userId).getBytes()));
        return this.baseMapper.selectImRecordList(imRecordDto,limit);
    }

    @Override
    public void read(ImRecordReq imRecordReq) {
        LambdaQueryWrapper<ImMessageRecordEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ImMessageRecordEntity::getChatIdentifier,
                Base64.getEncoder().encodeToString((imRecordReq.getUserId()+SecurityUser.getUserId()).getBytes()));
        ImMessageRecordEntity imMessageRecordEntity = new ImMessageRecordEntity();
        imMessageRecordEntity.setIsRead(Constant.ONE);
        baseMapper.update(imMessageRecordEntity,lambdaQueryWrapper);
    }
}
